package com.bw.controller.craft;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.order.PiOrder;
import com.bw.entity.order.PiOrderItem;
import com.bw.entity.user.TbUser;
import com.bw.entity.order.PiOrderLog;
import com.bw.resp.ResponseResult;
import com.bw.service.order.IPiOrderItemService;
import com.bw.service.order.IPiOrderLogService;
import com.bw.service.order.IPiOrderService;
import com.bw.service.user.ITbUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-20
 */
@RestController
@RequestMapping("/orderprocess")
public class PiOrderItemProcessController {
    @Autowired
    private IPiOrderService iPiOrderService;
    @Autowired
    private IPiOrderItemService iPiOrderItemService;
    @Autowired
    private IPiOrderLogService orderLogService;
    @Autowired
    private ITbUserService iTbUserService;

    private final Logger logger= LoggerFactory.getLogger(PiOrderItemProcessController.class);
    /**
     * 工艺列表模糊
     */
    @PostMapping("list/{page}/{size}")
    public ResponseResult list(@PathVariable("page") int page, @PathVariable("size") int size, @RequestBody PiOrder piOrder) { //参数json字符串
        logger.info("工艺列表列表查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(page, size);//开启分页查询
            QueryWrapper queryWrapper = new QueryWrapper();
            if (null!=piOrder.getCode()) {
                queryWrapper.like("code", "%" + piOrder.getCode() + "%");//模糊查询工艺编号

            }
            queryWrapper.in("state",1);
            queryWrapper.ne("isDelete",0);
            queryWrapper.orderByDesc("createDate");
            List<PiOrder> users = iPiOrderService.list(queryWrapper);//列表查询
            PageInfo pageInfo = new PageInfo(users);//pagehelper封装好的分页实体类，将数据放进去
            result.setResult(pageInfo);
        } catch (Exception e) {
            logger.info("工艺列表查询失败,{}",e.toString());
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
        }
        logger.info("工艺列表查询结束");
        return result;
    }
    /**
     * 工艺提交
     */
    @PostMapping("tjCraft/{id}")
    public ResponseResult tjOrder(@PathVariable("id") Integer id, @RequestBody TbUser tbUser) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiOrder piOrder= iPiOrderService.getById(id);
            piOrder.setState(2);
            piOrder.setTechnicianId(tbUser.getId());
            piOrder.setTechnologyDate(new Date());
            piOrder.setUpdateUser(tbUser.getId());
            piOrder.setUpdateDate(new Date());

            //根据订单id 获取订单零件表信息
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("orderId",id);
            List<PiOrderItem> list = iPiOrderItemService.list(wrapper);
            BigDecimal pricee = new BigDecimal("0");
            for (PiOrderItem piOrderItem1:list) {//循环符合当前订单下的所有订单信息
                if(piOrderItem1.getPrice()!=null){//判断该订单信息是否有钱（是否制作）
                    pricee=pricee.add(piOrderItem1.getPrice().multiply(new BigDecimal(piOrderItem1.getNum())));//总价钱算出来   单价*对应数量
                 }else{
                    result.setMessage(piOrderItem1.getName()+"未制作，请先返回制作");
                    result.setSuccess(false);
                    return result;
                }
            }
            piOrder.setPrice(pricee);//总价赋给订单表
            piOrder.setPriceIt(piOrder.getPrice().add(piOrder.getPrice().multiply(piOrder.getTaxRate().divide(new BigDecimal(100)))));//税后价钱
            iPiOrderService.saveOrUpdate(piOrder);

            PiOrderLog piOrderLog=new PiOrderLog();
            piOrderLog.setUserName(iTbUserService.getById(piOrder.getTechnicianId()).getFullName());
            piOrderLog.setOrderId(piOrder.getId());
            piOrderLog.setTbId(piOrder.getTbId());
            piOrderLog.setUpdatetime(new Date());
            piOrderLog.setRemarks("提交工艺");
            orderLogService.saveOrUpdate(piOrderLog);
            result.setMessage("提交成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("提交失败:" + e.toString());
        }
        return result;
    }
    /**
     * BOM回显
     */
    @PostMapping("get/{id}")
    public ResponseResult get(@PathVariable("id") Integer id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("orderid",id);
            List<PiOrderItem> lista=iPiOrderItemService.list(queryWrapper);
            result.setResult(lista);
            result.setMessage("提交成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("提交失败:" + e.toString());
        }
        return result;
    }
}
